import Taro, { Component } from '@tarojs/taro'
import { Swiper, SwiperItem, Image, View, Text, ScrollView } from '@tarojs/components'
import CommonJs from '../../utils/common'
import './consumer.scss'
import timg from '../../assets/kedouimg01/timg.png'

export default class Index extends Component {
  constructor(props) {
  	super(props);
    this.state = {
      result:[],
      znwns:'',
      pageNumber:0,
      hasNextPage:false,
      scrollPd:false,
      pageheight:0,
      navindex:1,
      myTime:null,
      iszy:0,
      ewm:"",
      status:'SUCCESSFUL'
    }
  }
  config = {
    navigationBarTitleText: '活动/消费订单'
  }

  componentWillMount () {
    var _this = this
    Taro.getSystemInfo({
      success:function(res){
        _this.setState({
          pageheight: res.windowHeight
        })
        _this.getUserOrder(0)
      }
    })
  }
  componentDidMount () {
    var _this = this
    var query = Taro.createSelectorQuery()
    query.select('.qun-bgbanner').boundingClientRect(function(rect){
      // console.log(JSON.stringify(rect)+'1111')
      var height=_this.state.pageheight
      _this.setState({
        pageheight:height-rect.height
      })
    }).exec()
  }
  componentWillUnmount () {
    clearTimeout(this.myTime)
  }
  getUserOrder(pageNumber){
    var _this=this
    var status=this.state.status;
    if(status){
      var url='/verify/papi/v1.9/consumption-order/consumptionPay?status.in='+status+'&page='+pageNumber
    }
    else{
      var url='/verify/papi/v1.9/consumption-order/consumptionPay?page='+pageNumber
    }
    CommonJs.ajaxRequest(url,'','GET',function(res){
     if(res.data.page<res.data.totalPages){
     		var hasNextPage = true
     	 }
     	 else{
     		var hasNextPage = false
        }
        
     	  var results = _this.state.result
         var result = res.data.list;
         if(pageNumber == 0){
            results = []
        }
     	  for(var i = 0; i < result.length; i++){
     		results.push(result[i])
     	  }
     	  if (hasNextPage) {
     		_this.setState({
          result:results,
          znwns: '暂无订单',
     		  pageNumber: res.data.page,
     		  hasNextPage: hasNextPage,
     		  scrollPd: true
     		})
     	  }
     	  else {
     		_this.setState({
          result:results,
          znwns: '暂无订单',
     		  pageNumber: res.data.page,
     		  hasNextPage: hasNextPage,
     		  scrollPd: false
     		})
     	  }

     },'wfw')
  }
  loadMore(){
    var _this = this
    var pd = _this.state.scrollPd
    if(pd) {
      //防止多次触发滑动到底部事件
      _this.setState({
        scrollPd: false//禁止下拉
      })
      var pageNumber = _this.state.pageNumber + 1
      _this.getUserOrder(pageNumber)
    }else{
      var hasNextPage =  _this.state.hasNextPage
      if(hasNextPage){
        Taro.showToast({
          title:'正在加载数据...',
          icon: 'none',
          duration: 2000
        })
      }else{
        Taro.showToast({
          title:'没有更多数据啦！',
          icon: 'none',
          duration: 2000
        })
      }
    }
  }
  gettrefund(id){
    //申请退款
    var _this=this
    Taro.showModal({
      title:'温馨提示',
      content:'确定申请退款？',
      success(ret){
        if(ret.confirm){
          var date={
            orderId:id
          }
          Taro.showLoading({title: '申请中'})
          var url='/verify/papi/v1.9/consumption-order/cancelConsume/'+id
          CommonJs.ajaxRequest(url,'','PUT',function(res){
            // console.log(JSON.stringify(res)+'//888888')
            Taro.hideLoading()
            Taro.showToast({
              title:'申请成功',
              icon: 'success',
              duration: 2000
            })
            _this.myTime = setTimeout(() => {
              _this.setState({
                result:[]
              },function(){
                _this.getUserOrder(1)
              })
            }, 2000)
          },'wfw')
        }
      }
    })
  }
  open(url){
    CommonJs.open(url)
  }
  doym(code){
  	var _this=this
  	var url="/consume/getVerifyCode?verifyCode="+code;
  	CommonJs.ajaxRequest(url,'','GET',function(res){
  		if(res.msg){
  			 var base64 = res.msg.replace(/[\r\n]/g, "")
  			 _this.setState({
		      iszy: 1,
		      ewm: base64
		    })
  		}

  	})
  }
  closedoym(){
  	this.setState({
      iszy:0,
      ewm:""
    })
  }
  changestates(status,val){
    this.setState({
      result:[],
      pageNumber:0,
      navindex:val,
      status:status
    })
    var _this=this;
    setTimeout(function(){
      _this.getUserOrder(0)
    },1000)
  }
  render () {
    const result = this.state.result
    return (
      <View className='page'>
        <View className='qun-bgbanner'>
          <Text className={this.state.navindex==1?'title activer':'title'} onClick={this.changestates.bind(this,'SUCCESSFUL',1)}>待消费</Text>
          <Text className={this.state.navindex==2?'title activer':'title'} onClick={this.changestates.bind(this,'UNVERIFIED',2)}>已消费</Text>
          <Text className={this.state.navindex==3?'title activer':'title'} onClick={this.changestates.bind(this,'',3)}>全部</Text>
        </View>
        <ScrollView className='qun-goods' scrollY='true' style={'height:'+this.state.pageheight+'px'} onScrollToLower={this.loadMore.bind(this,'')}>
        <View className='qun-znwn' style={result.length!=0?'display:none':'display:block'}>暂无订单</View>
          {result.map((item, index) => (
          <View className='activety-content'>

            <View className='activety-title'>
              <View className='activety-number'>{item.consumeOrder.serialno}</View>
              <View className='activety-refund' onClick={this.gettrefund.bind(this,item.id)} style={item.status!='CANCEL'&&item.status!='WAITING'?"":"display:none;"}>申请退款</View>
							<View className='activety-refund' style={item.status=='CANCEL'?"":"display:none;"}>已取消</View>
							<View className='activety-refund' style={item.status=='WAITING'?"":"display:none;"}>未付款</View>
            </View>
            <View className='activety-goods'>
              <View className='activety-goods-img'><Image mode='widthFix' className='activety-pic' src={item.project.logo?item.project.logo:timg}></Image></View>
              <View className='activety-right'>
              	<View className='activety-price fr'>
              		<Text className='activety-money'>实付:{item.payDetail.channelId==12?'UC':'￥'}{item.payAmount/100}</Text>
              		<View className='activety-code' onClick={this.doym.bind(this,item.verifyCode)} style={item.status!='WAITING'?"":"display:none;"}>
              			点击验证：{item.verifyCode}
              		</View>
              	</View>
                <View className='activety-goodsname'>{item.project.businessTypeId==2?'买单消费':item.project.name}</View>
                <View className='activety-value'>份数：{item.num?item.num:1}份</View>
                <View className='activety-time'>{CommonJs.FormatDate(item.createAt,3)}</View>
              </View>
            </View>
            <View className='activety-end' style={item.deductionList&&item.deductionList.length>0?'':'display:none'}>
           		  
           		  	{item.deductionList&&item.deductionList.map((item1, index1) => (
           		  		<Text>
           		  		{item1.payTypeId==211&&item1.amount>0?'抵扣'+item1.amount/100+'元共享金,':''}
           		  		{item1.payTypeId==212&&item1.amount>0?'抵扣'+item1.amount/100+'元消费金':''}
           		  		</Text>
           		  	))}
           		  
            </View>
            <View className='activety-end' style={item.userName?'':'display:none'}>
           		  <View className='activety-name'>联系人：{item.userName}({item.userPhone})</View>
                <View className='activety-beizhu'>备注：{item.remark}</View>
            </View>
            <View className='activety-end'>
            		<View className='paytype' style="float:right;line-height:50rpx;">{item.payDetail.channelId==12?'UC支付':item.payDetail.channelId==10?'余额支付':'微信支付'}</View>
           		  <View className='activety-name'>消费门店：{item.shopName.shopName}</View>
            </View>
            <View className='activety-goods-extra' style={item.consumptionCommodities&&item.consumptionCommodities.length>0?"":"display:none;"}>
            	<View className='extra-tit'>消费商品</View>
            	{item.consumptionCommodities&&item.consumptionCommodities.map((item1, index1) => (
            	<View className='activety-goods-li'>
	            	<View className='activety-goodsname'>
	            		<Text className='span02 fr'>{item1.price}积分+{item1.extraprice}元</Text>
	            		<Text className='span01'>{item1.commodityName}x{item1.amount}</Text>

	            	</View>
	            </View>
	            ))}
            </View>
            <View className='activety-goods-extra' style={item.comsumtionCouponList&&item.comsumtionCouponList.length>0?"":"display:none;"}>
            	<View className='extra-tit'>使用优惠券</View>
            	{item.comsumtionCouponList&&item.comsumtionCouponList.map((item1, index1) => (
            	<View className='activety-goods-li'>
	            	<View className='activety-goodsname'>
	            		<Text className='span02 fr'>-{item1.discountAmount!=null?item1.discountAmount/100:'0'}</Text>
	            		<Text className='span01'>{item1.name}</Text>
	            	</View>
	            </View>
	            ))}
            </View>

          </View>
          ))}
        </ScrollView>
        <View className='bg' style={this.state.iszy>=1?'display:block':'display:none;'} onClick={this.closedoym.bind(this)}></View>
        <View className='ydcon' style={this.state.iszy>=1?'display:block':'display:none;'}  onClick={this.closedoym.bind(this)}>
        	<View className='ydcon-ewm'>
        		<Image src={this.state.ewm?this.state.ewm:"https://minichat.g2ma.com/kedouimg/noimg.png"} mode='widthFix' className='activety-pic'></Image>
        		<Text className='ydcon-text'>出示给商家验证,点击关闭</Text>
        	</View>
        </View>
      </View>
    )
  }
}
